<template>
  <div class="app-container" style="padding: 8px;">
    <!--工具栏-->
    <div class="head-container">
      <div>
        <!-- 搜索 -->
        <el-input v-model="query.name" clearable size="small" placeholder="输入内容模糊搜索" style="width: 200px;" class="filter-item" @keyup.enter.native="search" />
        <date-range-picker v-model="query.createTime" class="date-item" />
        <el-select
          v-model="query.knowledgeType"
          class="filter-item"
          placeholder="文件目录"
        >
          <el-option
            v-for="(item, index) in knowledgeTypes"
            :key="item.label + index"
            :label="item.label"
            :value="item.label"
          />
        </el-select>
        <el-button class="filter-item" size="mini" type="success" icon="el-icon-search" @click="search">搜索</el-button>
        <el-button
          slot="left"
          class="filter-item"
          size="mini"
          type="primary"
          icon="el-icon-upload"
          @click="show"
        >上传
        </el-button>
      </div>
    </div>
    <!--表单组件-->
    <el-dialog
      append-to-body
      :visible.sync="dialogVisible"
      :close-on-click-modal="true"
      :title="crud.status.add ? '文件上传' : '编辑文件'"
      width="500px"
      @click="show"
    >
      <el-form ref="form" :model="form" size="small" label-width="80px">
        <el-form-item label="文件目录" prop="knowledgeType">
          <el-select
            v-model="form.knowledgeType"
            class="filter-item"
            placeholder="文件目录"
          >
            <el-option
              v-for="(item, index) in knowledgeTypes"
              :key="item.label + index"
              :label="item.label"
              :value="item.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="点击上传">
          <el-upload
            ref="upload"
            :file-list="files"
            :limit="1"
            :before-upload="beforeUpload"
            :auto-upload="false"
            :headers="headers"
            :data.sync="form"
            :on-success="handleSuccess"
            :on-error="handleError"
            :action="fileUploadApi"
          >
            <div class="eladmin-upload"><i class="el-icon-upload" /> 添加文件</div>
            <div slot="tip" class="el-upload__tip">可上传任意格式文件，且不超过100M</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="cancel">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </el-dialog>
    <!--表格渲染-->
    <el-table ref="table" v-loading="loading" :data="data" style="width: 100%;">
      <el-table-column prop="knowledgeType" label="文件目录" />
      <el-table-column prop="name" label="文件名">
        <template slot-scope="scope">
          <el-popover
            :content="scope.row.realName"
            placement="top-start"
            title="路径"
            width="200"
            trigger="hover"
          >
            <a
              slot="reference"
              :href="'/knowledge/' + scope.row.type +'/' + scope.row.realName"
              class="el-link--primary"
              style="word-break:keep-all;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color: #1890ff;font-size: 13px;"
              target="_blank"
            >
              {{ scope.row.name }}
            </a>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="size" label="大小" />
      <el-table-column prop="createBy" label="操作人" />
      <el-table-column :show-overflow-tooltip="true" prop="createTime" label="创建时间">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="checkPermission(['ADMIN','TSERVICEPROVIDERPERSON_ALL','TSERVICEPROVIDERPERSON_EDIT','TSERVICEPROVIDERPERSON_DELETE'])" label="操作" width="180px" align="center">
        <template slot-scope="scope">
          <el-popover
            :ref="scope.row.id"
            v-permission="['ADMIN','TSERVICEPROVIDERPERSON_ALL','TSERVICEPROVIDERPERSON_DELETE']"
            placement="top"
            width="180"
          >
            <p>确定删除本条数据吗？</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="$refs[scope.row.id].doClose()">取消</el-button>
              <el-button :loading="delLoading" type="primary" size="mini" @click="subDelete(scope.row.id)">确定</el-button>
            </div>
            <el-button slot="reference" type="danger" icon="el-icon-delete" size="mini" />
          </el-popover>
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <el-pagination
      :total="total"
      style="margin-top: 8px;"
      layout="total, prev, pager, next, sizes"
      @size-change="sizeChange"
      @current-change="pageChange"
    />
  </div>
</template>

<script>
import checkPermission from '@/utils/permission'
import { mapGetters } from 'vuex'
import initData from '@/mixins/initData'
import { getToken } from '@/utils/auth'
import { parseTime } from '@/utils/index'
import { getDictDetails } from '@/api/dictDetail'
import { del } from '@/api/tools/localStorage'
import CRUD, { presenter, crud } from '@crud/crud'
import DateRangePicker from '@/components/DateRangePicker'

const defaultForm = { id: null, name: '' }
export default {
  components: { DateRangePicker },
  cruds() {
    return CRUD({ title: '文件', url: 'api/localStorage' })
  },
  mixins: [initData, presenter(), crud()],
  data() {
    return {
      delLoading: false,
      loading: false,
      headers: { 'Authorization': 'Bearer ' + getToken() },
      dialogVisible: false,
      files: [],
      knowledgeTypes: [],
      form: this.crud.form,
      query: {}
    }
  },
  computed: {
    ...mapGetters([
      'baseApi',
      'fileUploadApi'
    ])
  },
  created() {
    this.getKnowledgeTypes('文件目录')
    this.$nextTick(() => {
      this.init()
    })
  },
  methods: {
    parseTime,
    checkPermission,
    beforeInit() {
      this.url = 'api/localStorage'
      const sort = 'id,desc'
      this.params = { page: this.page, size: this.size, sort: sort }
      const query = this.query
      if (query.name) {
        this.params['name'] = query.name
      }
      if (query.createTime) {
        this.params['createTime'] = query.createTime
      }
      if (query.knowledgeType) {
        this.params['knowledgeType'] = query.knowledgeType
      }
      return true
    },
    subDelete(id) {
      this.delLoading = true
      del(id).then(res => {
        this.delLoading = false
        this.$refs[id].doClose()
        this.init()
        this.$notify({
          title: '删除成功',
          type: 'success',
          duration: 2500
        })
      }).catch(err => {
        this.delLoading = false
        this.$refs[id].doClose()
        console.log(err)
      })
    },
    // 上传文件k'k'j
    submit() {
      this.$refs.upload.submit()
    },
    beforeUpload(file) {
      let isLt2M = true
      isLt2M = file.size / 1024 / 1024 < 100
      if (!isLt2M) {
        this.loading = false
        this.$message.error('上传文件大小不能超过 100MB!')
        return false
      }
      this.form.name = file.name
      // this.form.file = file
      return isLt2M
    },
    handleSuccess(response, file, fileList) {
      this.$notify({
        title: '添加成功',
        type: 'success',
        duration: 2500
      })
      const uid = file.uid
      console.log(fileList, response, uid)
      // const id = response.data[0]
      this.search()
      this.cancel()
      // this.files.push({ uid, name: id, url: '/api/picture/' + id })
    },
    // 监听上传失败
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 2500
      })
      this.loading = false
    },
    getKnowledgeTypes(dictName) {
      getDictDetails(dictName).then(res => { this.knowledgeTypes = res.content })
    },
    // 关闭
    cancel() {
      this.dialogVisible = false
    },
    // 显示
    show() {
      this.dialogVisible = true
    },
    search() {
      this.params.page = 0
      this.init()
    }
  }
}
</script>

<style scoped>
 ::v-deep .el-image__error, .el-image__placeholder{
    background: none;
  }
 ::v-deep .el-image-viewer__wrapper{
    top: 55px;
  }
</style>
